package com.geoai.feat_fc_control

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.geoai.basiclib.base.fragment.BaseVVDFragment
import com.geoai.basiclib.base.vm.EmptyViewModel
import com.geoai.basiclib.ext.isGone
import com.geoai.basiclib.ext.visible
import com.geoai.basiclib.utils.CoordinateConvertUtils
import com.geoai.basiclib.utils.LatLngUtils
import com.geoai.mavlink.geoainet.flycontroller.info.FlyControllerStateInfo
import com.geoai.modservice.di.ARouterPath
import com.geoai.uifccontrol.databinding.FragmentFlightStatusMenuBinding
import com.zkyt.lib_msdk_ext.component.FlyControllerManagerExt
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.addTo
import kotlinx.coroutines.launch
import kotlin.math.pow
import kotlin.math.sqrt

/**
 * @Author      : Ronny
 * @Email       : Ronny_xie@hotmail.com
 * @Date        : on 2024-04-10 09:58.
 * @Description :
 */
@Route(path = ARouterPath.PATH_CONTROL_FLIGHT_STATUS)
class FlightStatusFragment : BaseVVDFragment<EmptyViewModel, FragmentFlightStatusMenuBinding>() {

    override fun init(savedInstanceState: Bundle?) {
        getFlyControllerStateObservable {
            if (mBinding.menuFlightStatus.isGone) mBinding.menuFlightStatus.visible()

            val isAircraftPositionInValid = it.aircraftLatitude == 0.0 && it.aircraftLongitude == 0.0
            val distance: Double = LatLngUtils.getDistance(it.aircraftHomeLatitude, it.aircraftHomeLongitude, it.aircraftLatitude, it.aircraftLongitude)
            val vSpeed: Double = sqrt(it.aircraftVelocityX.toDouble().pow(2.0) + it.aircraftVelocityY.toDouble().pow(2.0))

            mBinding.tvFlightStatusHeight.text = String.format("%.2f m", it.aircraftAltitude)
            mBinding.tvFlightStatusHeightSpeed.text = String.format("%.2f m/s", -it.aircraftVelocityZ)
            mBinding.tvFlightStatusVerticalSpeed.text = String.format("%.2f m/s", vSpeed)
            mBinding.tvFlightStatusDistance.text = String.format("%.2f m", distance)

            if (isAircraftPositionInValid) mBinding.tvFlightStatusDistance.text = String.format("%.2f m", 0.0)
        }
    }

    //飞控状态数据监听
    private fun getFlyControllerStateObservable(block: (flyControllerState: FlyControllerStateInfo) -> Unit) {
        FlyControllerManagerExt.getFlyControllerStateObservable()
            .observeOn(AndroidSchedulers.mainThread())
            .filter{ it.isPresent }
            .subscribe {
                block.invoke(it.get())
            }.addTo(mViewModel.compositeDisposable)
    }
}